package com.android.ailaoshan.sound;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.recyclerview.widget.LinearLayoutManager;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.Switch;
import android.widget.Toast;

import com.android.ailaoshan.R;
import com.qmuiteam.qmui.widget.dialog.QMUIDialog;
import com.qmuiteam.qmui.widget.dialog.QMUIDialogAction;
import com.yanzhenjie.recyclerview.OnItemClickListener;
import com.yanzhenjie.recyclerview.SwipeRecyclerView;

import java.io.File;
import java.util.ArrayList;

public class SoundActivity extends AppCompatActivity implements OnItemClickListener {

    private Context mContext;

    private final String SOUND_PATH = Environment.getExternalStorageDirectory().getAbsolutePath()
            + File.separator +"AiLaoShan"+ File.separator + "Sound" + File.separator;

    private int protect = 2;

    private SoundAdapter adapter;
    private ArrayList<String> soundPathList;

    private int saveType = 1;
    private String rDescribe = "";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.sound_activity);

        mContext = SoundActivity.this;

        // 获取文件名List
        soundPathList = getIntent().getStringArrayListExtra("soundList");
        saveType = getIntent().getIntExtra("saveType",1);
        rDescribe = getIntent().getStringExtra("describe");

        SwipeRecyclerView recyclerView = findViewById(R.id.collection_sound_recycler);

        // 设置点击事件
        recyclerView.setOnItemClickListener(this);

        // 设置布局方式
        LinearLayoutManager layoutManager = new LinearLayoutManager(mContext);
        layoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        recyclerView.setLayoutManager(layoutManager);

        // 设置适配器
        adapter = new SoundAdapter(mContext);
        adapter.notifyDataSetChanged(soundPathList);
        recyclerView.setAdapter(adapter);

        // 尾布局，添加声音文件
/*        if(saveType != 3){
            View footView = getLayoutInflater().inflate(R.layout.item_add,recyclerView,false);
            footView.findViewById(R.id.collection_add_picture).setOnClickListener(
                    (v) -> {
                        Intent intent = new Intent(mContext,SoundRecorderActivity.class);
                        startActivityForResult(intent,213);
                    }
            );
            recyclerView.addFooterView(footView);
        }*/
    }

    @Override
    protected void onStart(){
        super.onStart();

        // 状态栏返回图标
        Toolbar toolbar = findViewById(R.id.collection_sound_voice_toolbar);
        toolbar.setNavigationOnClickListener(
            (v) -> {
                if(saveType != 3){
                    showExitMessage();
                }else{
                    finish();
                }
            }
        );

        // 是否保护
        Switch isProtect = findViewById(R.id.collection_sound_voice_switcher);
        isProtect.setOnCheckedChangeListener(
                (CompoundButton switcherBtn, boolean isSwitcher) -> {
                    if(protect == 2){
                        protect = 1;
                    }else{
                        protect = 2;
                    }
                }
        );

        // 保存
        Button saveBtn = findViewById(R.id.collection_sound_voice_save);
        if(saveType == 3){
            saveBtn.setVisibility(View.INVISIBLE);
        }
        EditText inputBox = findViewById(R.id.collection_text_input);
        inputBox.setText(rDescribe);
        saveBtn.setOnClickListener(
           (v) -> {
                if(soundPathList.size() > 0){
                    String description = inputBox.getText().toString().trim();

                    SoundManager soundManager = new SoundManager();
                    soundManager.saveSoundInfo(soundPathList,protect,description,saveType);
                }else{
                    Toast.makeText(mContext,"没有可保存的信息",Toast.LENGTH_SHORT).show();
                }
                finish();
           }
        );
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        switch (resultCode){
            case 602:{
                String deleteName = data.getStringExtra("deleteName");
                if( !deleteName.equals("") ){
                    soundPathList.remove(deleteName);
                    if(adapter != null){
                        adapter.notifyDataSetChanged(soundPathList);
                    }

                    // 删除本地文件
                    SoundManager soundManager = new SoundManager();
                    soundManager.deleteSoundFile(deleteName);
                }
                break;
            }
            default:break;
        }
    }

    /**
     * 点击了图片，开始播放
     */
    @Override
    public void onItemClick(View view, int position) {
        String soundPath = SOUND_PATH + soundPathList.get(position);
        File file = new File(soundPath);
        if(file.exists()){
            Intent intent = new Intent(mContext,PlayActivity.class);
            intent.putExtra("filePath",soundPath);
            intent.putExtra("saveType",saveType);
            startActivityForResult(intent,207);
        }else{
            Toast.makeText(mContext,"文件不存在或已损坏",Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * 点击了返回
     */
    @Override
    public void onBackPressed(){
        if(saveType != 3){
            showExitMessage();
        }else{
            finish();
        }
    }

    /**
     * 提示框
     */
    private void showExitMessage(){
        new QMUIDialog.MessageDialogBuilder(mContext)
                .setTitle("退出")
                .setMessage("现在退出这些记录将不能保存，确定退出吗？")
                .addAction("取消",new QMUIDialogAction.ActionListener() {
                    @Override
                    public void onClick(QMUIDialog dialog, int index) {
                        dialog.dismiss();
                    }
                }).addAction(0,"退出",QMUIDialogAction.ACTION_PROP_NEGATIVE,new QMUIDialogAction.ActionListener() {
                    @Override
                    public void onClick(QMUIDialog dialog, int index) {
                        dialog.dismiss();
                        if(soundPathList.size() > 0){
                            // 删除所有文件
                            SoundManager soundManager = new SoundManager();
                            soundManager.deleteAllSoundFile(soundPathList);
                        }

                        finish();
                    }
        }).create(R.style.QMUI_Dialog).show();
    }
}
